﻿using System;
using System.IO;

namespace Borg
{
    public class PathHelper
    {
        public static string GetFullPath(string path)
        {
            return
                path != null
                    ? (Path.IsPathRooted(path)
                           ? path
                           : Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path))
                    : null;
        }

        public static Uri ConvertToUri(string path)
        {
            return
                Uri.IsWellFormedUriString(path, UriKind.Absolute)
                    ? new Uri(path, UriKind.Absolute)
                    : new Uri(GetFullPath(path));
        }

        public static string[] GetFiles(string path)
        {
            path = GetFullPath(path);

            if (File.Exists(path))
                return new[] {Path.GetFullPath(path)};
            
            SearchOption searchOption;

            var srchPath = CutSearchOption(path, out searchOption);

            return
                Directory.Exists(srchPath)
                    ? Directory.GetFiles(srchPath, "*.*", searchOption)
                    : null;
        }

        public static string[] GetDirectories(string path)
        {
            path = GetFullPath(path);

            if (File.Exists(path))
                return new[] {Path.GetDirectoryName(path)};

            if (Directory.Exists(path))
                return new[] {path};
            
            SearchOption searchOption;
            var srchPath = CutSearchOption(path, out searchOption);

            return
                Directory.Exists(srchPath)
                    ? Directory.GetDirectories(srchPath, "*", searchOption)
                    : null;
        }

        private static string CutSearchOption(string path, out SearchOption searchOption)
        {
            if (path.EndsWith("\\**"))
            {
                searchOption = SearchOption.AllDirectories;
                return path.Substring(0, path.Length - 2);
            }
            
            searchOption = SearchOption.TopDirectoryOnly;

            return
                path.EndsWith("\\*")
                    ? path.Substring(0, path.Length - 1)
                    : path;
        }
    }
}
